package model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * This class is used to store/retrieve informations as CSV.
 * It implements the {@link PersistentStorage} interface.
 * @author Sacha MASSON
 */
public class LoadFromCSV {

	/**
	 * Filename of the CSV file
	 */
	private static final String FILENAME = "contactlist.csv";
	
	/**
	 * Character used as a separator
	 */
	private static final String SEMICOLON = ",";
	
	/**
	 * If the separator is used, we replace it by this string
	 */
	private static final String SEMICOLON_REPLACE = "||SEMICOLON||";

		public static List<Contact> load() {
		List<Contact> list = Collections.synchronizedList(new ArrayList<Contact>());
		try(Reader r = new FileReader(new File(FILENAME))) {
			try(BufferedReader br = new BufferedReader(r)) {
				String line;
				while((line = br.readLine()) != null) {
					list.add(parse(line));
				}
                                
				return list;
                                
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return Collections.synchronizedList(new ArrayList<Contact>());
	}
	
	/**
	 * Parse a line of CSV file and return a {@link Contact} object
	 * @param line of CSV file
	 * @return {@link Contact}
	 */
	public static Contact parse(String line) {
		String[] elements = line.split(",");
		
		return new Contact(elements[0], elements[1],
				elements[2], elements[3], elements[4],
				elements[5], elements[6], elements[7],elements[8],
				Integer.parseInt(elements[9]));		
	}
}